package com.yifi.common.handler;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import com.jfinal.handler.Handler;
import com.jfinal.kit.HttpKit;
import com.yifi.common.model.Syslog;
import com.yifi.common.utils.StringUtils;
import com.yifi.common.utils.ToolDateTime;
import com.yifi.common.utils.ToolRandoms;
import com.yifi.common.utils.ToolWeb;
import com.yifi.common.utils.UserAgentUtil;

import cz.mallat.uasparser.UserAgentInfo;

public class GlobalHandler extends Handler {

	private static Logger log = Logger.getLogger(GlobalHandler.class);

	@Override
	public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
		// TODO Auto-generated method stub
		log.debug("初始化访问系统功能日志");
		Syslog reqSysLog = getSysLog(request);
		long starttime = ToolDateTime.getDateByTime();
		// reqSysLog.set(Syslog.startdate,
		// ToolDateTime.getSqlTimestamp(starttime)); // 开始时间
		request.setAttribute("reqSysLog", reqSysLog);

		log.debug("设置 web 路径");
		String cxt = ToolWeb.getContextPath(request);
		request.setAttribute("cxt", cxt);

		log.debug("request 随机分配一个请求id");
		request.setAttribute("id", ToolRandoms.getUuid(true));

		log.debug("request cookie 处理");
		Map<String, Cookie> cookieMap = ToolWeb.readCookieMap(request);
		request.setAttribute("cookieMap", cookieMap);

		log.debug("request param 请求参数处理");
		request.setAttribute("paramMap", ToolWeb.getParamMap(request));

		log.debug("设置Header");
		//request.setAttribute("decorator", "none");
		//response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
		//response.setHeader("Pragma", "no-cache"); // HTTP 1.0
		//response.setDateHeader("Expires", 0); // prevents caching at the proxy
		
		
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Methods","*"); //使用通配符
        response.addHeader("Access-Control-Allow-Headers","Content-Type,Access-Token,Authorization");  //使用通配符
        response.addHeader("Access-Control-Expose-Headers", "*");
        if (request.getMethod().equals("OPTIONS")) {  
            //HttpUtil.setResponse(response, HttpStatus.OK.value(), null);  
            return;
        }

		nextHandler.handle(target, request, response, isHandled);

		log.debug("请求处理完毕，计算耗时");

		// 结束时间
		long endtime = ToolDateTime.getDateByTime();
		reqSysLog.set(Syslog.column_enddate, ToolDateTime.getSqlTimestamp(endtime));

		// 总耗时
		Long haoshi = endtime - starttime;
		reqSysLog.set(Syslog.column_haoshi, haoshi);

		// 视图耗时
		long renderTime = 0;
		if (null != request.getAttribute("renderTime")) {
			renderTime = (Long) request.getAttribute("renderTime");
		}

		reqSysLog.set(Syslog.column_viewhaoshi, renderTime);

		// action耗时
		reqSysLog.set(Syslog.column_actionhaoshi, haoshi - renderTime);

		log.debug("日志添加到入库队列");
		if (reqSysLog.getSyslog() != null) {
			if (reqSysLog.getSyslog().equals("1")) {
				// ThreadSysLog.add(reqSysLog);
				if (StringUtils.isNotEmpty(reqSysLog.getDescription())) {
					reqSysLog.save();
				}
			}
		}
	}

	/**
	 * 创建日志对象,并初始化一些属性值
	 * 
	 * @param request
	 * @return
	 */
	public Syslog getSysLog(HttpServletRequest request) {
		String requestPath = ToolWeb.getRequestURIWithParam(request);
		String ip = ToolWeb.getIpAddr(request);
		String referer = request.getHeader("Referer");
		String userAgent = request.getHeader("User-Agent");
		UserAgentInfo userAgentInfo = null;
		try {
			userAgentInfo = UserAgentUtil.uasParser.parse(userAgent);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String cookie = "";	//request.getHeader("Cookie");
		String method = request.getMethod();
		String xRequestedWith = request.getHeader("X-Requested-With");
		String host = request.getHeader("Host");
		String acceptLanguage = request.getHeader("Accept-Language");
		String acceptEncoding = request.getHeader("Accept-Encoding");
		String accept = request.getHeader("Accept");
		String connection = request.getHeader("Connection");
		
		//获取请求体数据，url后边的拼接参数数据    不能从这里拦截，要不然后边的controller中无法获取参数值
		//String jsonData = HttpKit.readData(request);
		
		Syslog reqSysLog = new Syslog();

		/*
		 * reqSysLog.set("ips",ip); reqSysLog.set("requestPath", requestPath);
		 * reqSysLog.set("referer",referer);
		 * reqSysLog.set("useragent",userAgent); reqSysLog.set("cookie",cookie);
		 * reqSysLog.set("method",method);
		 * reqSysLog.set("xrequestedwith",xRequestedWith);
		 * reqSysLog.set("host",host);
		 * reqSysLog.set("acceptlanguage",acceptLanguage);
		 * reqSysLog.set("acceptencoding",acceptEncoding);
		 * reqSysLog.set("accept",accept);
		 * reqSysLog.set("connection",connection);
		 */

		reqSysLog.set(Syslog.column_ips, ip);
		reqSysLog.set(Syslog.column_requestpath, requestPath);
		reqSysLog.set(Syslog.column_referer, referer);
		reqSysLog.set(Syslog.column_useragent, userAgent);

		if (userAgentInfo != null) {
			
			/*System.out.println("操作系统名称：" + userAgentInfo.getOsFamily());//
			System.out.println("操作系统：" + userAgentInfo.getOsName());//
			System.out.println("浏览器名称：" + userAgentInfo.getUaFamily());//
			System.out.println("浏览器版本：" + userAgentInfo.getBrowserVersionInfo());//
			System.out.println("设备类型：" + userAgentInfo.getDeviceType());
			System.out.println("浏览器:" + userAgentInfo.getUaName());
			System.out.println("类型：" + userAgentInfo.getType());*/
			
			//系统参数
			reqSysLog.set("osfamily", userAgentInfo.getOsFamily());
			reqSysLog.set("osname", userAgentInfo.getOsName());
			reqSysLog.set("uafamily", userAgentInfo.getUaFamily());
			reqSysLog.set("browserversioninfo", userAgentInfo.getBrowserVersionInfo());
			reqSysLog.set("devicetype", userAgentInfo.getDeviceType());
			reqSysLog.set("uaname", userAgentInfo.getUaName());
			reqSysLog.set("type", userAgentInfo.getType());

		}

		reqSysLog.set(Syslog.column_cookie, cookie);
		reqSysLog.set(Syslog.column_method, method);
		reqSysLog.set(Syslog.column_xrequestedwith, xRequestedWith);
		reqSysLog.set(Syslog.column_host, host);
		reqSysLog.set(Syslog.column_acceptlanguage, acceptLanguage);
		reqSysLog.set(Syslog.column_acceptencoding, acceptEncoding);
		reqSysLog.set(Syslog.column_accept, accept);
		reqSysLog.set(Syslog.column_connection, connection);

		return reqSysLog;
	}

}
